package com.xunji.standard.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class ExecutorUtils {

    @Value("${thread.core.num:5}")
    private int coreNum; // 核心线程数

    @Value("${thread.max.num:20}")
    private int maxNum; // 最大线程数

    @Value("${thread.queue.size:1024}")
    private int queueSize;


    @PostConstruct
    public void postConstruct() {
        if (executorService == null) {
            executorService = new ThreadPoolExecutor(coreNum, maxNum,
                    100L, TimeUnit.MILLISECONDS,
                    new ArrayBlockingQueue<>(queueSize),
                    new DefaultThreadFactory());
        }
    }

    private static ExecutorService executorService;

    public static void execute(Runnable runnable) {

        executorService.execute(runnable);
    }

    static class DefaultThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        DefaultThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            namePrefix = "TH-execute-pool-" +
                    poolNumber.getAndIncrement() +
                    "-thread-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                    namePrefix + threadNumber.getAndIncrement(),
                    0);
            if (t.isDaemon())
                t.setDaemon(false);
            t.setPriority(Thread.MAX_PRIORITY - 2);
            return t;
        }
    }
}